package com.aijia.custom.product.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.aijia.custom.product.R;
import com.aijia.custom.product.adapter.OrderAdapter;
import com.aijia.custom.product.customview.ClearEditText;
import com.aijia.custom.product.customview.LoadingWaitDialog;
import com.aijia.custom.product.customview.NoDoubleClickListener;
import com.aijia.custom.product.data.DayCountData;
import com.aijia.custom.product.data.SheetData;
import com.aijia.custom.product.data.WSheetData;
import com.aijia.custom.product.listener.IDayCountListener;
import com.aijia.custom.product.listener.IWSheetListListener;
import com.aijia.custom.product.manager.DayCountManager;
import com.aijia.custom.product.manager.WSheetManager;
import com.aijia.custom.product.ui.AddOrderActivity;
import com.aijia.custom.product.ui.OrderItemActivity;
import com.aijia.custom.product.utils.AddOrderHelper;
import com.aijia.custom.product.utils.ArtStatusHelper;
import com.aijia.custom.product.utils.Notification;
import com.aijia.custom.product.utils.Utils;
import com.powerfulrecyclerview.listener.OnRefreshListener;
import com.powerfulrecyclerview.ptr.HistoryThemeHeaderView;
import com.powerfulrecyclerview.ptr.PowerfulRecyclerView;
import com.powerfulrecyclerview.ptr.SimDividerItemDecoration;

import java.util.List;

/**
 * Created by yejianjun on 2019/4/22.
 */

public class OrderFragment extends LazyLoadBaseFragment implements View.OnClickListener, OnRefreshListener, OrderAdapter.OnItemClickListener, IWSheetListListener, ArtStatusHelper.IArtStatusListener, IDayCountListener, AddOrderHelper.IDataChangerListener {

    private ImageButton rightBtn;
    private Button todayBtn, sevenBtn, thirthBtn;

    private Dialog pDialog;
    private int startPage = 0;
    private int ROW = 10;

    private PowerfulRecyclerView recyclerView;
    private RecyclerView.LayoutManager mLayoutManager;
    private HistoryThemeHeaderView header;
    // 是否上拉加载更多
    private int lastVisibleItem = 0;

    private OrderAdapter adapter;
    private WSheetManager manager;
    private DayCountManager dayCountManager;
    private ImageView searchIV;
    private ClearEditText searchET;
    /**
     * 搜索内容
     */
    private String query_str;
    /**
     * 当天：0 近7天：6 近30天：29 默认0；查询今天数据
     */
    private int currentDays = 0;
    private final int DAY_ONE = 0;
    private final int DAY_SEVEN = -6;
    private final int DAY_THIRTH = -29;
    private TextView addTV;


    public static OrderFragment instance() {
        OrderFragment view = new OrderFragment();
        //在该Fragment的构造函数中注册mTouchListener的回调
        return view;
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.fragment_order;
    }

    @Override
    protected void initView(View view) {
        initTitle(view);
        todayBtn = view.findViewById(R.id.today_btn);
        sevenBtn = view.findViewById(R.id.seven_btn);
        thirthBtn = view.findViewById(R.id.thirty_btn);
        recyclerView = view.findViewById(R.id.order_listview);

        todayBtn.setOnClickListener(noDoubleClickListener);
        sevenBtn.setOnClickListener(noDoubleClickListener);
        thirthBtn.setOnClickListener(noDoubleClickListener);

        searchIV = (ImageView) view.findViewById(R.id.in_pro_search_iv);
        searchIV.setOnClickListener(this);
        searchET = (ClearEditText) view.findViewById(R.id.search_item_number_et);

        initData();

        reqData(currentDays);
        // 请求天统计数据
        reqDayCount();

        searchET.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    searchAction();
                    return true;
                }
                return false;
            }
        });
    }

    private void initTitle(View view) {
        rightBtn = view.findViewById(R.id.right_imageButton);
        rightBtn.setOnClickListener(this);
        rightBtn.setVisibility(View.GONE);
        addTV = view.findViewById(R.id.right_text_tv);
        addTV.setText("新增");
        addTV.setVisibility(View.VISIBLE);
        addTV.setOnClickListener(noDoubleClickListener);
    }

    private void initData() {
        recyclerView.setAdapter(adapter);
        mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        // 设置布局管理器
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new SimDividerItemDecoration(getContext()));
        // 设置adapter
        header = (HistoryThemeHeaderView) LayoutInflater.from(getContext()).inflate(R.layout.history_header_theme, recyclerView, false);
        recyclerView.setHeaderView(header);
        recyclerView.setLoadMoreEnable(false);
        recyclerView.setRefreshing(true);
        recyclerView.setOnRefreshListener(this);
        initLoadMoreListener();
    }

    /**
     * 上拉加载更多
     */
    private void initLoadMoreListener() {
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == adapter.getItemCount() && adapter.getItemCount() >= ROW + 1) {
                    //设置正在加载更多
                    adapter.changeMoreStatus(OrderAdapter.LOADING_MORE);
                    startPage++;
                    reqData(currentDays);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //最后一个可见的ITEM
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        adapter = new OrderAdapter(getContext());
        adapter.setOnItemClickListener(this);
        adapter.changeMoreStatus(OrderAdapter.PULLUP_LOAD_MORE);
        initManager();
    }

    private void initManager() {
        manager = new WSheetManager(getActivity());
        manager.addWSheetLisListener(this);
        dayCountManager = new DayCountManager(getActivity());
        dayCountManager.addDayCountListener(this);
        ArtStatusHelper.getInstance().addListener(this);
        AddOrderHelper.getInstance().addListener(this);
    }

    private void reqData(int day) {
        manager.wSheetList(day, startPage * ROW, ROW, query_str);
    }

    private void reqDayCount() {
        dayCountManager.dayCount();
    }

    NoDoubleClickListener noDoubleClickListener = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            switch (v.getId()) {
                case R.id.today_btn:
                    currentDays = DAY_ONE;
                    changeDayStatus();
                    showDialog();
                    startPage = 0;
                    reqData(currentDays);
                    break;
                case R.id.seven_btn:
                    currentDays = DAY_SEVEN;
                    changeDayStatus();
                    showDialog();
                    startPage = 0;
                    reqData(currentDays);
                    break;
                case R.id.thirty_btn:
                    currentDays = DAY_THIRTH;
                    changeDayStatus();
                    showDialog();
                    startPage = 0;
                    reqData(currentDays);
                    break;
                case R.id.right_text_tv:
                    Intent intent = new Intent();
                    intent.setClass(getContext(), AddOrderActivity.class);
                    startActivity(intent);
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_imageButton:

                break;
            case R.id.in_pro_search_iv:
                searchAction();
                break;
            default:
                break;
        }
    }

    private void searchAction() {
        Utils.hideSoftInput(getContext(), searchET);
        // 按了查询按钮，默认把页面置0
        startPage = 0;
        showDialog();
        query_str = searchET.getText().toString().trim();
        reqData(currentDays);
    }

    private void showDialog() {
        pDialog = LoadingWaitDialog.createLoadingDialog(getContext(), "");
        pDialog.show();
    }


    @Override
    public void onRefresh() {
        startPage = 0;
        reqData(currentDays);
        reqDayCount();
    }

    @Override
    public void itemClick(View view) {
        int position;
        switch (view.getId()) {
            case R.id.order_item_layout:
                position = (Integer) view.getTag(R.id.order_item_layout);

                Intent intent = new Intent();
//                intent.putExtra("_id", adapter.getList().get(position).getId());
                intent.setClass(getContext(), OrderItemActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    @Override
    public void onWSheetListFailure(int errorCode, String errorMsg) {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        Notification.toast(getActivity(), errorMsg == null ? "" : errorMsg);
        adapter.changeMoreStatus(OrderAdapter.NO_LOAD_MORE);
        recyclerView.stopRefresh();
    }

    @Override
    public void onWSheetListSuccess(List<WSheetData> list) {
        adapter.changeMoreStatus(OrderAdapter.NO_LOAD_MORE);
        recyclerView.stopRefresh();
        if (startPage == 0) {
            adapter.clear();
            adapter.setData(list);
        } else {
            adapter.insertData(list);
        }
        adapter.notifyDataSetChanged();
        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                if (null != pDialog && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
            }
        });
    }

    @Override
    public void updateStatus(int wsheetId, int artId, int status, String finishDate) {
        adapter.updateStatus(wsheetId, artId, status, finishDate);
    }

    @Override
    public void updateFinishDate(int wsheetId, String finishDate) {

    }

    @Override
    public void updateRemark(int wsheetId, String content) {

    }

    @Override
    public void updateListStatus(int wsheetId, int status) {
        adapter.updateListStatus(wsheetId, status);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ArtStatusHelper.getInstance().removeListener(this);
        AddOrderHelper.getInstance().removeListener(this);
        if (null != manager) {
            manager.removeWSheetLisListener(this);
        }
        if (null != dayCountManager)
            dayCountManager.removeDayCountListener(this);
    }

    @Override
    public void onDayCountFailure(int errorCode, String errorMsg) {
        /*if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }*/
    }

    @Override
    public void onDayCountSuccess(DayCountData data) {
        if (null == data)
            return;
        todayBtn.setText(getContext().getResources().getString(R.string.today, data.day1));
        sevenBtn.setText(getContext().getResources().getString(R.string.seven_days, data.day7));
        thirthBtn.setText(getContext().getResources().getString(R.string.thirty_month, data.day30));
    }

    private void changeDayStatus() {
        switch (currentDays) {
            case DAY_ONE:
                todayBtn.setBackgroundResource(R.drawable.shape_green);
                sevenBtn.setBackgroundResource(R.drawable.gray_button_bg);
                thirthBtn.setBackgroundResource(R.drawable.gray_button_bg);
                break;
            case DAY_SEVEN:
                todayBtn.setBackgroundResource(R.drawable.gray_button_bg);
                sevenBtn.setBackgroundResource(R.drawable.shape_green);
                thirthBtn.setBackgroundResource(R.drawable.gray_button_bg);
                break;
            case DAY_THIRTH:
                todayBtn.setBackgroundResource(R.drawable.gray_button_bg);
                sevenBtn.setBackgroundResource(R.drawable.gray_button_bg);
                thirthBtn.setBackgroundResource(R.drawable.shape_green);
                break;
            default:
                break;
        }
    }


    @Override
    public void refreshDate() {
        startPage = 0;
        reqData(currentDays);
        reqDayCount();
    }

    @Override
    public void updateInfo(SheetData data) {

    }
}
